import { useEffect, useState, useCallback } from 'react';

import Link from 'next/link';
import { useRouter } from 'next/router';

import useTranslation from '@/hooks/useTranslation';

import { getQueryId } from '@/utils/common';
import { findLastLeafId, findSelectedMessageByLeafId } from '@/utils/message';

import { ChatStatus, IChat } from '@/types/chat';
import { IChatMessage, IStepGenerateInfo } from '@/types/chatMessage';

import { ChatMessage } from '@/components/ChatMessage';
import { IconArrowCompactDown } from '@/components/Icons/index';
import PageNotFound from '@/components/PageNotFound/PageNotFound';
import { Button } from '@/components/ui/button';

import { getChatShare } from '@/apis/clientApis';

export default function ShareMessage() {
  const { t } = useTranslation();
  const router = useRouter();
  const [selectedChat, setSelectedChat] = useState<IChat | null>(null);
  const [messages, setMessages] = useState<IChatMessage[]>([]);
  const [selectedMessages, setSelectedMessages] = useState<IChatMessage[][]>(
    [],
  );
  const [loading, setLoading] = useState(true);
  const [showBottomBar, setShowBottomBar] = useState(true);
  const [chatShareId, setChatShareId] = useState<string>('');

  const handleToggleBottomBar = () => {
    setShowBottomBar(!showBottomBar);
  };

  const handleChangeChatLeafMessageId = (messageId: string) => {
    const leafId = findLastLeafId(messages, messageId);
    const selectedMsgs = findSelectedMessageByLeafId(messages, leafId);
    setSelectedMessages(selectedMsgs);
  };


  useEffect(() => {
    setLoading(true);
    if (!router.isReady) return;
    const shareId = getQueryId(router)!;
    setChatShareId(shareId);
    getChatShare(shareId).then((data) => {
      setSelectedChat({ ...data, status: ChatStatus.None });
      setMessages(data.messages);
      let selectedMsgs = findSelectedMessageByLeafId(
        data.messages,
        data.leafMessageId!,
      );
      if (selectedMsgs.length === 0 && data.messages.length > 0) {
        const messageCount = data.messages.length - 1;
        selectedMsgs = findSelectedMessageByLeafId(
          data.messages,
          data.messages[messageCount].id,
        );
      }
      setSelectedMessages(selectedMsgs);
      setLoading(false);
    });
  }, [router.isReady]);

  const MessageRender = () => {
    return selectedChat ? (
      <>
        <div className={`${showBottomBar ? 'pb-32' : 'pb-12'}`}>
          <ChatMessage
            selectedChat={selectedChat}
            selectedMessages={selectedMessages}
            messagesEndRef={null}
            readonly={true}
            chatShareId={chatShareId}
            onChangeChatLeafMessageId={handleChangeChatLeafMessageId}
          />
        </div>
        {showBottomBar ? (
          <div className="fixed bottom-0 left-0 w-full border-transparent bg-background z-50">
            <div className="flex justify-center mx-auto w-full px-2 md:px-4">
              <div className="relative flex w-full flex-grow flex-col rounded-md bg-card shadow-[0_0_10px_rgba(0,0,0,0.10)] dark:shadow-[0_0_15px_rgba(0,0,0,0.10)] p-4">
                <div className="absolute mb-1 bottom-full mx-auto flex w-full justify-center z-10">
                  <Button
                    className="rounded-sm p-1 m-1 text-neutral-800 bg-card hover:bg-card w-auto h-auto"
                    onClick={handleToggleBottomBar}
                  >
                    <IconArrowCompactDown />
                  </Button>
                </div>
                <div className="flex justify-center pb-2">
                  <Link href="/">
                    <Button className="h-8 w-32">{t('Using Chats')}</Button>
                  </Link>
                </div>
                <div className="flex justify-center text-gray-500 text-sm">
                  {t(
                    'Content shared by other users, generated by AI big model, please screen carefully',
                  )}
                </div>
              </div>
            </div>
          </div>
        ) : (
          <div className="fixed bottom-0 left-0 w-full border-transparent bg-background z-50">
            <div className="flex justify-center w-full">
              <Button
                className="rounded-sm p-1 m-1 text-neutral-800 bg-card hover:bg-card w-auto h-auto"
                onClick={handleToggleBottomBar}
              >
                <IconArrowCompactDown className={'rotate-180'} />
              </Button>
            </div>
          </div>
        )}
      </>
    ) : (
      <PageNotFound />
    );
  };

  return loading ? <></> : MessageRender();
}
